package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <dl>
 * <dd>描述: ~节点业务逻辑实现</dd>
 * <dd>创建时间：  18:47 2020/3/11</dd>
 * <dd>创建人： zz</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2020/3/11      guodong       1.0        1.0 Version
 * </pre>
 * </dl>
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }

    /**
    * @Date: 19:24 2020/3/11
    * @Param: []
    * @return: java.lang.String
    * @Description: redis做缓存
    **/
    @GetMapping
    public String findAllStr(){

        //1.查询缓存
        String userStr = (String) redisTemplate.boundValueOps("user.findAllStr").get();
        //1.2 不存在
        if(StringUtils.isEmpty(userStr)){
            log.info("redis中不存在userStr查询数据库");
            //1.3查询数据库并将数据json格式化放入redis中，再返回
            List<User> userList = userService.findAll();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                userStr = objectMapper.writeValueAsString(userList);
                redisTemplate.boundValueOps("user.findAllStr").set(userStr);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        //1.1 存在
        return userStr;
    }




}
